<?php

/**
 * Mediad co,ltd
 *
 * @category   Mediad2
 * @package    Mediad2_Service
 * @subpackage Util
 * @copyright  Copyright (c) 2012 Mediad co,ltd. (http://www.Mediad.cn)
 * @license    New BSD License
 * @version    $Id: NotifierError.php 1 2012-04-13 15:19:00Z vincent@Mediad.cn $
 */

class Mediad2_Service_Util_NotifierError
{
	protected $_environment;
	protected $_mailer;
	protected $_session;
	protected $_error;

	public function __construct(
			$environment,
			$error,
			Mediad2_Service_Util_Email $mailer,
			Zend_Session_Namespace $session,
			Array $server)
	{
		$this->_environment = $environment;
		$this->_mailer = $mailer;
		$this->_error = $error;
		$this->_session = $session;
		$this->_server = $server;
	}

	public function getFullErrorMessage()
	{
		$message = '';

		if (!empty($this->_server['SERVER_ADDR'])) {
			$message .= "Server IP: " . $this->_server['SERVER_ADDR'] . "\n";
		}

		if (!empty($this->_server['HTTP_USER_AGENT'])) {
			$message .= "User agent: " . $this->_server['HTTP_USER_AGENT'] . "\n";
		}

		if (!empty($this->_server['HTTP_X_REQUESTED_WITH'])) {
			$message .= "Request type: " . $this->_server['HTTP_X_REQUESTED_WITH'] . "\n";
		}

		$message .= "Server time: " . date("Y-m-d H:i:s") . "\n";
		$message .= "RequestURI: " . $this->_error->request->getRequestUri() . "\n";

		if (!empty($this->_server['HTTP_REFERER'])) {
			$message .= "Referer: " . $this->_server['HTTP_REFERER'] . "\n";
		}

		$message .= "Message: " . $this->_error->exception->getMessage() . "\n\n";
		$message .= "Trace:\n" . $this->_error->exception->getTraceAsString() . "\n\n";
		$message .= "Request data: " . var_export($this->_error->request->getParams(), true) . "\n\n";

		$it = $this->_session->getIterator();

		$message .= "Session data:\n\n";
		foreach ($it as $key => $value) {
			$message .= $key . ": " . var_export($value, true) . "\n";
		}
		$message .= "\n";

		return $message;
	}

	public function getShortErrorMessage()
	{
		$message = '';

		switch ($this->_environment) {
			case 'staging':
				$message .= "It seems you have just encountered an unknown issue.";
				$message .= "Our team has been notified and will deal with the problem as soon as possible.";
				break;
			default:
				$message .= "Message: " . $this->_error->exception->getMessage() . "\n\n";
			$message .= "Trace:\n" . $this->_error->exception->getTraceAsString() . "\n\n";
		}

		return $message;
	}

	public function notify()
	{
		if (!in_array($this->_environment, array('staging', 'testing', 'development'))) {
			return false;
		}

		return $this->_mailer->sendException($this->getFullErrorMessage());
	}
}
